package edu.uci.ics.xmlrpc;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;

public class ClientConsole{		

	// both of these are the "teambananas2" server
	//static String server = "http://teambananas2.ics.uci.edu:80/xmlrpc";
	//static String server = "http://128.195.30.164:988/xmlrpc";

	//static String server = "http://169.234.14.7:8080/xmlrpc"; //Matt
	//static String server = "http://169.234.12.54:8080/xmlrpc"; //Alex
	static String server = "http://169.234.3.86:8080/xmlrpc"; //Dan
	

	public static void main(String args[])
	{
		String userFrom = "";
		String userTo = "";
		String message = "";

	      //  open up standard input
	      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	      
	      try
	      {
	    	  while(!userFrom.equals("EXIT"))
	    	  {
		    	  //  prompt the user to enter their name
	    		  System.out.println();
			      System.out.print("FROM: ");
			      
		    	  userFrom = br.readLine();
		    	  if(userFrom.equals("EXIT")) break;
		    	  
		    	  System.out.print("TO: ");
		    	  
		    	  userTo = br.readLine();
		    	  
		    	  System.out.print("MESSAGE: ");
		    	  message = br.readLine();
		    	  
		    	  send(userFrom, userTo, message);
	    	  }
	      }
	      catch(Exception e) {
	    	  e.printStackTrace();
	      }
	      
	      System.out.println("Messaging client terminated");
	}
	
	// send a message to the Server for re-routing to another ChatterClient
	public static void send(String userFrom, String userTo, String message) throws Exception
	{
		//String userFrom = "Client1"; // user the message originates from
		//String userTo = "Client2"; // user the message is destined for
		//String message = "I am a message"; // whatever message you would like
		
		// create configuration
        XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
        config.setServerURL(new URL(server));
        config.setEnabledForExtensions(true);  
        config.setConnectionTimeout(60 * 1000);
        config.setReplyTimeout(60 * 1000);

        XmlRpcClient client = new XmlRpcClient();
      
        // use Commons HttpClient as transport
        client.setTransportFactory(
            new XmlRpcCommonsTransportFactory(client));
        // set configuration
        client.setConfig(config);

        // make the a regular call
        Object[] params = new Object[]
            { new String(userFrom), new String(userTo), new String(message) };
        client.execute("ChatterServer.sendMessageTo", params);
        
        System.out.println("Sent from " + userFrom + " to " + userTo + ": " + message);
        //System.out.println(config.getUserAgent());
	}
}
